<?php

namespace App\Http\Controllers\Mini;

use App\Http\Controllers\Home\PaymentController;
use App\Models\ActivityCategorys;
use App\Models\Activitys;
use App\Models\Ads;
use App\Models\Buys;
use App\Models\Collections;
use App\Models\Configs;
use App\Models\Footprints;
use App\Models\IntegralLogs;
use App\Models\SignUps;
use App\Models\Users;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ActivityController extends Controller
{
    /**
     * 活动分类
     * @route api.act.actCate
     */
    public function actCate(Request $request){
        try{
            $lists = ActivityCategorys::getCascaderList();
            $fields = ['id','thumb','title','start_at','view','cost','number','cate_pid','cate_id'];
            foreach ($lists as $k=>$v){//获取分类下的热门活动、最新活动
                $lists[$k]['hot'] = Activitys::allLists(['hot'=>2],$fields, null,3);
                $lists[$k]['new'] = Activitys::allLists([],$fields, null,3);
                foreach ($lists[$k]['hot'] as $key=>$val){
                    $lists[$k]['hot'][$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
                    $lists[$k]['hot'][$key]['number'] = strlen($val['number'])>=4 ? '999+' : $val['number'];
                    $lists[$k]['hot'][$key]['start_at'] = trim(@date('Y-m-d', strtotime($val['start_at'])));
                    $lists[$k]['hot'][$key]['enroll_at'] = trim(@date('Y-m-d', strtotime($val['enroll_at'])));
                }
                foreach ($lists[$k]['new'] as $key=>$val){
                    $lists[$k]['new'][$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
                    $lists[$k]['new'][$key]['number'] = strlen($val['number'])>=4 ? '999+' : $val['number'];
                    $lists[$k]['new'][$key]['start_at'] = trim(@date('Y-m-d', strtotime($val['start_at'])));
                    $lists[$k]['new'][$key]['enroll_at'] = trim(@date('Y-m-d', strtotime($val['enroll_at'])));
                }
                //获取分类下的广告
                $params = [
                    'cate_id' => $v['value'],
                    'adsense_id' => 35,
                    'status' => 1,
                    'limit' => 1,
//                    'start_at' => date('Y-m-d H:i:s'),
//                    'end_at' => date('Y-m-d H:i:s'),
                ];
                $lists[$k]['adv'] = Ads::getList($params, ['id','adsense_id','thumb','link']);
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 活动筛选
     * @route api.act.actScreen
     */
    public function actScreen(Request $request){
        try{
            $lists = ActivityCategorys::getCascaderList();

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 活动列表
     * @route api.act.actLists
     * @param cid_id 二级分类id
     * @param page 页码
     * @param limit 条数
     * @param sid 排序 1收藏量 2浏览量 3报名量
     */
    public function actLists(Request $request){
        try{
            $cid_id = $request->post('cid_id');//二级分类id
            if (!empty($cid_id)){
                $map['cid_id'] = explode(",", $cid_id);
            }else {
                $map['cid_id'] = null;
            }
            $page = (int)$request->post('page',1);//页码
            $limit = (int)$request->post('limit',5);//条数
            $sid = (int)$request->post('sid');//排序 1收藏量 2浏览量 3报名量
            if ($sid == 1){
                $sort = 'collect';
            }elseif ($sid == 2){
                $sort = 'view';
            }elseif ($sid == 3){
                $sort = 'number';
            }else{
                $sort = 'created_at';
            }
            $fields = ['id','thumb','title','start_at','view','cost','number','enroll_at','start_at','cate_pid','cate_id'];
            $lists = Activitys::allLists($map, $fields, $page, $limit, $sort, 'desc');
            $now_time = date('Y-m-d H:i:s');
            foreach ($lists as $key=>$val){
                $lists[$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
                $lists[$key]['number'] = strlen($val['number'])>=4 ? '999+' : $val['number'];
                $lists[$key]['start_at'] = trim(@date('Y-m-d', strtotime($val['start_at'])));
                $lists[$key]['enroll_at'] = trim(@date('Y-m-d', strtotime($val['enroll_at'])));
                if($now_time <= $val['enroll_at']){
                    $lists[$key]['act_state'] = '报名中';
                }elseif ($now_time >= $val['start_at']){
                    $lists[$key]['act_state'] = '已举办';
                }else{
                    $lists[$key]['act_state'] = '报名结束';
                }
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 活动详情
     * @route api.act.actDetails
     * @param user_id 用户id
     * @param act_id 活动id
     * @return is_act 0:不可报名 1:可报名
     * @return is_collect 0:未收藏 1:已收藏
     * @return is_sign_up 0:未报名 1:已报名
     */
    public function actDetails(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            $user_info = Users::where('id',$user_id)->where('status','<>',-1)->first();

            $act_id = (int)$request->post('act_id');//活动id
            if (empty($act_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);

            $now_time = date('Y-m-d H:i:s');
            $lists = Activitys::details(['id'=>$act_id], ['*']);
            $lists['view'] = strlen($lists['view'])>=4 ? '999+' : $lists['view'];
            $lists['number'] = strlen($lists['number'])>=4 ? '999+' : $lists['number'];
            $lists['is_act'] = 1;//默认可报名
            if($now_time <= $lists['enroll_at']){
                $lists['act_state'] = '报名中';
                $lists['is_act'] = 1;//可报名
            }elseif ($now_time >= $lists['start_at']){
                $lists['act_state'] = '已举办';
                $lists['is_act'] = 0;//不可报名
            }else{
                $lists['act_state'] = '报名结束';
                $lists['is_act'] = 0;//不可报名
            }
            //判断是否收藏和报名
            $lists['is_collect'] = 0;//默认未收藏
            $lists['is_sign_up'] = 0;//默认未报名
            if (!empty($user_info)){
                if($user_info['type'] == 1){
                    //收藏
                    $collect = Collections::where(['collect_id'=>$act_id,'user_id'=>$user_info['id'],'type'=>5])->value('collect_id');
                    $lists['is_collect'] = empty($collect) ? 0 : 1;
                    //报名
                    $sign_up = SignUps::where(['activity_id'=>$act_id, 'user_id'=>$user_info['id']])->where('status','<>',-1)->value('activity_id');
                    $lists['is_sign_up'] = empty($sign_up) ? 0 : 1;
                }
                //添加足迹
                $foot_arr = [
                    'user_id' => $user_info['id'],
                    'foot_id' => $act_id,
                    'type'    => 4,
                ];
                Footprints::create($foot_arr);
            }
            //主办方信息
            if($lists['source'] == 1){
                $base = Configs::getConfig('base');
                $lists['link_phone'] = $base['customer_mobile'];
            }
            Activitys::where('id',$act_id)->increment('view');//浏览量加1

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 收藏活动
     * @route api.act.actCollect
     * @param user_id 用户id
     * @param collect_id 收藏内容id
     */
    public function actCollects(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $userinfo = Users::where(['id'=>$user_id, 'status'=>1])->value('type');
            if (empty($userinfo)) return response()->json(["code"=>0, "msg"=>'用户不存在']);
            if ($userinfo != 1) return response()->json(["code"=>0, "msg"=>'供应商不能收藏']);
            $collect_id = (int)$request->post('collect_id');
            if (empty($collect_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $collect = Collections::where(['collect_id'=>$collect_id, 'user_id'=>$user_id, 'type'=>5])->value('id');
            if (empty($collect)){
                $params = [
                    'collect_id' => $collect_id,
                    'user_id' => $user_id,
                    'collect_at' => date('Y-m-d H:i:s'),
                    'type' => 5,
                ];
                Collections::create($params);
                Activitys::where('id',$collect_id)->increment('collect');
                return response()->json(["code"=>1, "msg"=>'收藏成功']);
            }else {
                Collections::where(['collect_id'=>$collect_id, 'user_id'=>$user_id, 'type'=>5])->delete();
                return response()->json(["code"=>1, "msg"=>'取消收藏成功']);
            }
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * HR报名活动
     * @route api.act.actSignUp
     * @param user_id 用户id
     * @param activity_id 活动id
     * @param number 参与人数
     * @param type 类型：1收费 2免费
     * @param money 总价
     * @param price 单价
     */
    public function actSignUp(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $fields = ['id','username','sex','mobile','email','type'];
            $userinfo = Users::getUserInfo(['id'=>$user_id],$fields);
            if (empty($userinfo)) return response()->json(["code"=>0, "msg"=>'用户不存在']);
            if ($userinfo['type'] != 1) return response()->json(["code"=>0, "msg"=>'供应商不能报名活动']);

            $activity_id = (int)$request->post('activity_id');//活动id
            $number = (int)$request->post('number');//参与人数
            $type = (int)$request->post('type');//类型：1收费 2免费
            if (empty($activity_id) || empty($number) || empty($type)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $sign_up = SignUps::where(['user_id'=>$user_id,'activity_id'=>$activity_id])->value('id');
            if (!empty($sign_up)) return response()->json(["code"=>0, "msg"=>'您已报名此活动']);

            $money = (int)$request->post('money');//总价
            $price = (int)$request->post('price');//单价

            $params = [
                'pay_sn' => Buys::makePaySn($activity_id),
                'activity_id' => $activity_id,
                'user_id' => $user_id,
                'user_name' => $userinfo['username'],
                'sex' => $userinfo['sex'],
                'phone' => $userinfo['mobile'],
                'email' => $userinfo['email'],
                'company' => $userinfo['user_info']['company_name'],
                'department' => $userinfo['user_info']['hr_department'],
                'position' => $userinfo['user_info']['hr_position'],
                'type' => $userinfo['user_info']['company_type'],
                'industry' => $userinfo['user_info']['company_industry'],
                'size' => $userinfo['user_info']['company_size'],
                'hr_size' => $userinfo['user_info']['hr_size'],
                'number' => $number,
            ];
            if($type == 2){//免费
                $params['money'] = 0;
                $params['price'] = 0;
                $params['charge'] = 2;
                $params['pay_state'] = 2;
                $params['pay_at'] = date('Y-m-d H:i:s');
            }elseif ($type == 1){//收费
                $params['money'] = $money;
                $params['price'] = $price;
                //TOOD
            }
            $sign_info = SignUps::create($params);
            if($sign_info['charge'] = 1){
                //根据订单信息，生成支付二维码
                $order_info = SignUps::where(array('pay_sn'=>$sign_info['pay_sn']))->first();
                $order_act = Activitys::where(array('id'=>$order_info['activity_id']))->first();
                $detail = $order_act['title'].'支付订单';
                $notify_url = route('home.payment.actNotifyUrl');
                $payment = new PaymentController();
                $ret=$payment->wxPayment($sign_info['pay_sn'], $order_info['activity_id'],$order_info['money'],'支付订单',$detail,$notify_url,'JSAPI');

                if($ret['code'] !== 1){
                    return response()->json([
                        "code"=>1,
                        "msg"=>'支付失败',
                        "data"=>$ret
                    ]);
                }
            }

            $integral = Configs::getConfig('integral');
            Activitys::where('id',$params['activity_id'])->increment('number');//报名人数加1
            Users::where('id',$user_id)->increment('integral',$integral['hr_activity']);//报名活动送积分
            //添加日志记录
            $integral = [
                'user_id' => $user_id,
                'user_name' => $userinfo['username'],
                'integral' => '+'.$integral['hr_activity'],
                'type' => 1,
                'desc' => '报名活动送积分',
            ];
            IntegralLogs::create($integral);

            return response()->json(["code"=>1, "msg"=>'报名成功', 'data'=>$activity_id]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 活动报名结果
     * @route api.act.actSignUpResult
     * @param act_id 活动id
     */
    public function actSignUpResult(Request $request){
        try{
            $act_id = (int)$request->post('act_id');//活动id
            if (empty($act_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);

            $lists = Activitys::details(['id'=>$act_id], ['id','title','cost','charge','cate_pid','cate_id']);

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

}